package com.future.scan.proxy;

import com.future.spring.annotation.Component;
import com.future.spring.annotation.Order;
import com.future.spring.context.BeanPostProcessor;
import com.future.spring.exception.BeansException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


/**
 * @author weber
 * @Description:
 * @Date 2025/8/4 15:32
 */
@Order(200)
@Component
public class SecondProxyBeanPostProcessor implements BeanPostProcessor {

    final Logger logger = LoggerFactory.getLogger(getClass());

    Map<String, Object> originBeans = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (OriginBean.class.isAssignableFrom(bean.getClass())) {
            logger.debug("Creating second proxy for bean '{}': {}", beanName, bean);
            var proxyBean = new SecondProxyBean((OriginBean) bean);
            originBeans.put(beanName, proxyBean);
            return proxyBean;
        }
        return bean;
    }

    @Override
    public Object postProcessOnSetProperty(Object bean, String beanName) throws BeansException {
        Object origin = originBeans.get(beanName);
        if (origin != null) {
            logger.debug("auto set property for {} from second proxy: {} to origin bean {}", beanName, bean, origin);
            return origin;
        }
        return bean;
    }
}
